package com.yztc.youbadbad.http;

import com.yztc.youbadbad.config.UrlConfig;
import com.yztc.youbadbad.helper.OkHttp3Helper;
import com.yztc.youbadbad.utils.FileManger;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Tiffany.V.Chou on 2016/11/14.
 */

public class HttpUtils {
    private static volatile HttpUtils singleton;

    private IRetrofitApi iApi;
    private Retrofit retrofit;

    private HttpUtils() {
        init();
    }

    public static HttpUtils getInstance() {
        if (singleton == null) {
            synchronized (HttpUtils.class) {
                if (singleton == null) {
                    singleton = new HttpUtils();
                }
            }
        }
        return singleton;
    }

    private void init() {
        retrofit=new Retrofit.Builder()
                .baseUrl(UrlConfig.BASE_URL)
                .client(OkHttp3Helper.getOkHttpSingletonInstance())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //.client(client())
                .build();

    }

    public IRetrofitApi getIApi(){
        if(iApi==null)
            iApi = retrofit.create(IRetrofitApi.class);
        return iApi;
    }

    private OkHttpClient client() {

        Cache cache=new Cache(FileManger.getHttpCache(),20*1024*1024);

        //OkHttpClient client=new OkHttpClient.Builder()
        OkHttpClient client= OkHttp3Helper.getOkHttpSingletonInstance().newBuilder()
                .cache(cache)
                .readTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20,TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS)
                .build();

        return client;
    }

}
